﻿//*** Guidance generated code ***//
using System;
using System.Collections.Generic;
using System.Linq;

using ProjectBase.Core;

using $prjsn$.Entity;
using $prjsn$.Common;
using $prjsn$.Common.Validation;

namespace $safeprojectname$
{
    public class AdditionalCustomListRule<TEntity> : RuleBase, IValidationRule<TEntity>
        where TEntity : class, IBusinessObject
    {
        #region members

        private readonly string _customListDiscriminator;
        private IField _field;

        #endregion members

        #region Constructor

        public AdditionalCustomListRule(string customListDiscriminator, IField field)
        {
            PropertyName = field.PropertyName;
            _field = field;
            _customListDiscriminator = customListDiscriminator;
        }

        #endregion Constructor

        #region Validate

        public virtual ValidationResult Validate(TEntity entity, out ValidationMessage message)
        {
            message = null;

            if (entity.IsNull())
            {
                return ValidationResult.IsValid;
            }

            var customList = entity.Additional[PropertyName] as CustomList;

            if (customList.IsNull())
            {
                return ValidationResult.IsValid;
            }

            var isCorrectSubType = customList.CustomListTypeName.IsEqual(_customListDiscriminator);

            // the Value of the KEY is null
            if (isCorrectSubType)
            {
                return ValidationResult.IsValid;
            }

            var itemId = entity.IsTransient() ? "new" : entity.IDToDisplay;

            message = new ValidationMessage(Str.Messages.ValidationIncorrectCustomList5)
            {
                itemId,
                typeof(TEntity).Name,
                "Additional." + PropertyName,
                CustomListDiscriminator,
                customList.CustomListTypeName,
            };
            return ValidationResult.Error;
        }

        #endregion Validate

        #region properties

        protected virtual IField Field
        {
            get { return _field; }
            set { _field = value; }
        }

        protected virtual string CustomListDiscriminator
        {
            get { return _customListDiscriminator; }
        }

        #endregion properties
    }
}